package com.jshoperxms.controller.mall.backstage.goods;

import com.jshoperxms.Response;
import com.jshoperxms.components.upload.qiniu.ImgFileBean;
import com.jshoperxms.controller.mall.backstage.base.BaseTController;
import com.jshoperxms.controller.mall.backstage.base.IBaseCtrl;
import com.jshoperxms.controller.mall.backstage.base.SearchModel;
import com.jshoperxms.controller.mall.backstage.vo.request.GoodsBean;
import com.jshoperxms.controller.utils.BaseTools;
import com.jshoperxms.controller.utils.DateTools;
import com.jshoperxms.controller.utils.enums.BaseEnums;
import com.jshoperxms.controller.utils.json.GsonJson;
import com.jshoperxms.controller.utils.statickey.SerialKeys;
import com.jshoperxms.controller.utils.statickey.StaticKey;
import com.jshoperxms.controller.utils.statickey.TagWords;
import com.jshoperxms.controller.utils.statickey.WarnWrods;
import com.jshoperxms.entity.GoodsDetailRpT;
import com.jshoperxms.entity.GoodsT;
import com.jshoperxms.entity.ProductT;
import com.jshoperxms.service.GoodsDetailRpTService;
import com.jshoperxms.service.GoodsTService;
import com.jshoperxms.service.ProductTService;
import com.jshoperxms.service.impl.Serial;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by sdywcd on 16/10/14.
 * Des:商品逻辑
 */
@Controller
@RequestMapping("/mall/goods")
public class GoodsTController extends BaseTController implements IBaseCtrl<GoodsT>{

    @Resource
    private GoodsTService goodsTService;
    @Resource
    private ProductTService productTService;
    @Resource
    private GoodsDetailRpTService goodsDetailRpTService;

    private Map<String,Object> responsedata=new HashMap<>();

    @Override
    public ResponseEntity save(@RequestBody GoodsT rq) {
       return null;
    }


    @RequestMapping(value="/save",method= RequestMethod.POST)
    public ResponseEntity saveGoods(@RequestBody GoodsBean rq) {
        GoodsT bean=new GoodsT();
        bean.setGoodsid(this.serial.Serialid(SerialKeys.GOODST));
        bean.setAllsales(rq.getAllsales());
        bean.setAlltotalcomment(rq.getAlltotalcomment());
        bean.setAlltotalzan(rq.getAlltotalzan());
        bean.setAllvsales(rq.getAllvsales());
        bean.setCommoditylist(rq.getCommoditylist());
        bean.setCreatetime(DateTools.getSystemTimeBi());
        bean.setCreatorid(BaseTools.getAdminCreateId());
        bean.setGoodsname(rq.getGoodsname());
        bean.setSubgoodsname(rq.getSubgoodsname());
        bean.setGoodstypeid(rq.getGoodstypeid());
        bean.setGoodstypename(rq.getGoodstypename());
        bean.setIsoutsite(rq.getIsoutsite());
        bean.setBrandid(rq.getBrandid());
        bean.setBrandname(rq.getBrandname());
        Map<String,String>map=BaseTools.parseImg(rq.getMainimg());
        bean.setMainimg(map.get(TagWords.NORMALFILEPATH));
        bean.setSmainimg(map.get(TagWords.COMPRESSFILEPATH));
        List<ImgFileBean>imgs= GsonJson.parseJsonToData(rq.getImgs(),ImgFileBean.class);
        List<String>imgsstr=new ArrayList<>();
        List<String>simgsstr=new ArrayList<>();
        for(ImgFileBean img:imgs){
            imgsstr.add(img.getNormalfilepath());
            simgsstr.add(img.getCompressfilepath());
        }
        bean.setImgs(StringUtils.join(imgsstr,TagWords.SPLITDOT));
        bean.setSimgs(StringUtils.join(simgsstr,TagWords.SPLITDOT));
        bean.setMetades(rq.getMetades());
        bean.setMetakey(rq.getMetakey());
        bean.setNavid(rq.getNavid());
        bean.setNname(rq.getNname());
        bean.setLname(rq.getLname());
        bean.setLtypeid(rq.getLtypeid());
        bean.setStypeid(rq.getStypeid());
        bean.setSname(rq.getSname());
        bean.setOutsitelink(rq.getOutsitelink());
        bean.setSname(rq.getSname());
        bean.setStypeid(rq.getStypeid());
        bean.setSort(rq.getSort());
        bean.setStoreid(StaticKey.EMPTY);
        bean.setStorename(StaticKey.EMPTY);
        bean.setStatus(rq.getStatus());
        bean.setMsync(rq.getMsync());
        bean.setPattrs(StaticKey.EMPTY);
        bean.setMinprice(rq.getMinprice());
        bean.setMaxprice(rq.getMaxprice());
        bean.setServicecode(rq.getServicecode());
        bean.setUpdatetime(DateTools.getSystemTimeBi());
        bean.setVersiont(1);
        this.goodsTService.saveGoodsTransactional(bean,rq.getDetail(),rq.getProductids());
        responsedata.put(TagWords.SUCCESS, true);
        responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
        return Response.success(responsedata);
    }

    @RequestMapping(value="/find",method= RequestMethod.POST)
    @Override
    public ResponseEntity find(@RequestBody GoodsT rq) {
        if(StringUtils.isBlank(rq.getGoodsid())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG, WarnWrods.ERROR_PARAMS);
        }else{
            GoodsT bean=this.goodsTService.findByPK(GoodsT.class,rq.getGoodsid());
            if(bean!=null){
                ImgFileBean ifb=new ImgFileBean();
                ifb.setNormalfilepath(bean.getMainimg());
                ifb.setCompressfilepath(bean.getSmainimg());
                ifb.setBasepath(StaticKey.EMPTY);
                List<ImgFileBean>ifbs=new LinkedList<>();
                String imgs[]=StringUtils.split(bean.getImgs(),TagWords.SPLITDOT);
                String simgs[]=StringUtils.split(bean.getSimgs(),TagWords.SPLITDOT);
                if(imgs!=null&&imgs.length>0){
                    for(int i=0;i<imgs.length;i++){
                        ImgFileBean ifbi=new ImgFileBean();
                        ifbi.setNormalfilepath(imgs[i]);
                        if(simgs.length>0){
                            ifbi.setCompressfilepath(simgs[i]);
                        }else{
                            ifbi.setCompressfilepath(StaticKey.EMPTY);
                        }

                        ifbi.setBasepath(StaticKey.EMPTY);
                        ifbs.add(ifbi);
                    }
                }
                responsedata.put(TagWords.IFB,ifb);
                responsedata.put(TagWords.IFBS,ifbs);
                responsedata.put(TagWords.BEAN,bean);
            }
            Criterion criterion=Restrictions.and(Restrictions.eq("goodsid", bean.getGoodsid())).add(Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState()));
            List<ProductT>plist=this.productTService.findByCriteria(ProductT.class, criterion);
            if(!plist.isEmpty()){
                responsedata.put(TagWords.PBEANLISTS,plist);
            }
            GoodsDetailRpT gd=this.goodsDetailRpTService.findOneByCriteria(GoodsDetailRpT.class, criterion);
            if(gd!=null){
                responsedata.put(TagWords.GDBEAN,gd);
            }
        }
        responsedata.put(TagWords.SUCCESS,true);
        responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
        return Response.success(responsedata);
    }


    @RequestMapping(value="/del",method= RequestMethod.POST)
    @Override
    public ResponseEntity del(@RequestBody GoodsT rq) {
        if(StringUtils.isBlank(rq.getGoodsid())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }else{
            this.goodsTService.delGoodsTransactional(rq.getGoodsid());
            responsedata.put(TagWords.SUCCESS,true);
            responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
        }
        return Response.success(responsedata);
    }

    @Override
    public ResponseEntity update(@RequestBody GoodsT rq) {
        return null;
    }


    @RequestMapping(value="/update",method= RequestMethod.POST)
    public ResponseEntity updateGoods(@RequestBody GoodsBean rq) {
        if(StringUtils.isBlank(rq.getGoodsid())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }else{
            GoodsT bean=this.goodsTService.findByPK(GoodsT.class,rq.getGoodsid());
            if(bean!=null){
                bean.setAllsales(rq.getAllsales());
                bean.setAlltotalcomment(rq.getAlltotalcomment());
                bean.setAlltotalzan(rq.getAlltotalzan());
                bean.setAllvsales(rq.getAllvsales());
                bean.setCommoditylist(rq.getCommoditylist());
                bean.setGoodsname(rq.getGoodsname());
                bean.setSubgoodsname(rq.getSubgoodsname());
                bean.setGoodstypeid(rq.getGoodstypeid());
                bean.setGoodstypename(rq.getGoodstypename());
                bean.setIsoutsite(rq.getIsoutsite());
                bean.setBrandid(rq.getBrandid());
                bean.setBrandname(rq.getBrandname());
                Map<String,String>map=BaseTools.parseImg(rq.getMainimg());
                bean.setMainimg(map.get(TagWords.NORMALFILEPATH));
                bean.setSmainimg(map.get(TagWords.COMPRESSFILEPATH));
                List<ImgFileBean>imgs= GsonJson.parseJsonToData(rq.getImgs(),ImgFileBean.class);
                List<String>imgsstr=new ArrayList<>();
                List<String>simgsstr=new ArrayList<>();
                for(ImgFileBean img:imgs){
                    imgsstr.add(img.getNormalfilepath());
                    simgsstr.add(img.getCompressfilepath());
                }
                bean.setImgs(StringUtils.join(imgsstr,TagWords.SPLITDOT));
                bean.setSimgs(StringUtils.join(simgsstr,TagWords.SPLITDOT));
                bean.setMetades(rq.getMetades());
                bean.setMetakey(rq.getMetakey());
                bean.setNavid(rq.getNavid());
                bean.setNname(rq.getNname());
                bean.setLname(rq.getLname());
                bean.setLtypeid(rq.getLtypeid());
                bean.setStypeid(rq.getStypeid());
                bean.setSname(rq.getSname());
                bean.setOutsitelink(rq.getOutsitelink());
                bean.setSname(rq.getSname());
                bean.setStypeid(rq.getStypeid());
                bean.setSort(rq.getSort());
                bean.setStoreid(StaticKey.EMPTY);
                bean.setStorename(StaticKey.EMPTY);
                bean.setStatus(rq.getStatus());
                bean.setMsync(rq.getMsync());
                //bean.setPattrs(rq.getPattrs());
                bean.setMinprice(rq.getMinprice());
                bean.setMaxprice(rq.getMaxprice());
                bean.setServicecode(rq.getServicecode());
                bean.setUpdatetime(DateTools.getSystemTimeBi());
                bean.setVersiont(bean.getVersiont()+1);
                this.goodsTService.updateGoodsTransactional(bean,rq.getDetail(),rq.getProductids());
                responsedata.put(TagWords.SUCCESS, true);
                responsedata.put(TagWords.MSG, TagWords.OPERATION_SUCCESS);
            }
        }
        return Response.success(responsedata);
    }

    @Override
    public ResponseEntity findAll() {
        return null;
    }


    @RequestMapping(value="/findByPage",method= RequestMethod.POST)
    @Override
    public ResponseEntity findByPage(SearchModel searchModel, @RequestParam("search[value]") String search, @RequestParam("order[0][column]") String ordervalue, @RequestParam("order[0][dir]") String ordertype) {
        findCustomSearch(searchModel,search,ordervalue,ordertype);
        return Response.success(responsedata);
    }

    @Override
    public void findCustomSearch(SearchModel searchModel, String search, String ordervalue, String ordertype) {
        if(searchModel.getIsCustomSearch()==1){
            int currentPage=searchModel.getCalCurrentPage();
            int lineSize = searchModel.getLength();
            Criterion criterion=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
            if(StringUtils.isNotBlank(searchModel.getName())){
                criterion=Restrictions.and(criterion).add(Restrictions.like("goodsname",searchModel.getName(), MatchMode.ANYWHERE));
            }
            if(StringUtils.isNotBlank(search)){
                criterion=Restrictions.and(criterion).add(Restrictions.like("goodsname",search,MatchMode.ANYWHERE));
            }
            int records=this.goodsTService.count(GoodsT.class,criterion).intValue();
            searchModel.setRecordsTotal(records);
            searchModel.setRecordsFiltered(records);
            responsedata.put(TagWords.RECORDSTOTAL,records);
            responsedata.put(TagWords.RECORDSFILTERED,records);
            List<GoodsT> list = this.goodsTService.findByCriteriaByPage(
                    GoodsT.class, criterion, Order.desc(TagWords.UPDATETIME), currentPage,
                    lineSize);
            this.processPageList(list);

        }else{
            if(StringUtils.isNotBlank(search)){
                filterSearch(searchModel,search);
            }else{
                findDefaultAll(searchModel,ordervalue,ordertype);
            }
        }
    }

    @Override
    public void filterSearch(SearchModel searchModel, String search) {
        int currentPage=searchModel.getCalCurrentPage();
        int lineSize = searchModel.getLength();
        Criterion criterion=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
        criterion=Restrictions.and(criterion).add(Restrictions.like("goodsname",search,MatchMode.ANYWHERE));
        int records=this.goodsTService.count(GoodsT.class,criterion).intValue();
        searchModel.setRecordsTotal(records);
        searchModel.setRecordsFiltered(records);
        responsedata.put(TagWords.RECORDSTOTAL,records);
        responsedata.put(TagWords.RECORDSFILTERED,records);
        List<GoodsT> list = this.goodsTService.findByCriteriaByPage(
                GoodsT.class, criterion,Order.desc(TagWords.UPDATETIME), currentPage,
                lineSize);
        this.processPageList(list);
    }

    @Override
    public void findDefaultAll(SearchModel searchModel, String ordervalue, String ordertype) {
        int currentPage=searchModel.getCalCurrentPage();
        int lineSize = searchModel.getLength();
        Criterion criterion=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
        int records=this.goodsTService.count(GoodsT.class,criterion).intValue();
        searchModel.setRecordsFiltered(records);
        searchModel.setRecordsTotal(records);
        responsedata.put(TagWords.RECORDSTOTAL,records);
        responsedata.put(TagWords.RECORDSFILTERED,records);
        Order order=BaseTools.orderByParam("goodsname",ordervalue,ordertype);
        List<GoodsT> list = this.goodsTService.findByCriteriaByPage(
                GoodsT.class, criterion,order, currentPage,
                lineSize);
        this.processPageList(list);
    }

    @Override
    public void processPageList(List<GoodsT> list) {
        List<Map<String,Object>>data=new ArrayList<>();
        for(GoodsT bean:list){
            if(StringUtils.isBlank(bean.getSmainimg())){
                bean.setSmainimg(bean.getMainimg());
            }
            Map<String,Object>cellMap=new HashMap<>();
            cellMap.put("id",bean.getGoodsid());
            cellMap.put("smainimg",bean.getSmainimg());
            cellMap.put("goodsname",bean.getGoodsname());
            cellMap.put("nname",bean.getNname()+TagWords.HR+bean.getLname()+TagWords.HR+bean.getSname());
            cellMap.put("goodstypename",bean.getGoodstypename());
            cellMap.put("price",bean.getMinprice().toString()+TagWords.HR+bean.getMaxprice().toString());
            cellMap.put("sort", bean.getSort());
            cellMap.put("status", BaseEnums.DataUsingState.getName(bean.getStatus()));
            cellMap.put("updatetime", DateTools.formateLongDateToString(bean.getUpdatetime().longValue()));
            cellMap.put("version", bean.getVersiont());
            data.add(cellMap);
        }
        responsedata.put(TagWords.DATA,data);
    }

    @Override
    public boolean checkDuplicates(String str) {
        return false;
    }
}
